<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
    <el-form-item label="站点编号：">
      <el-input v-model="ruleForm.id" disabled class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="站点类型">
      <el-radio-group @change="inputToDisabled(ruleForm.type)" v-model="ruleForm.type">
        <el-radio label="1">供热</el-radio>
        <el-radio label="2">需热</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="所属用户：">
      <el-select v-model="ruleForm.uid" placeholder="请选择" class="selWidth" clearable filterable>
        <el-option :value="item.uid" v-for="(item, index) in userList" :key="index" :label="item.realName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item id="inputPriceItem" label="单价（元/kwh）：">
      <el-input id="inputPrice" v-model="ruleForm.price" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="站点名称：">
      <el-input v-model="ruleForm.name" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="站点图标" prop="icon">
      <div class="upLoadPicBox" @click="modalPicTap('1', 'icon')">
        <div v-if="ruleForm.cover" class="pictrue"><img :src="ruleForm.cover"></div>
        <div v-else class="upLoad">
          <i class="el-icon-camera cameraIconfont" />
        </div>
      </div>
    </el-form-item>
    <el-form-item label="IMEI：">
      <el-input v-model="ruleForm.imei" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="排放类型：">
      <el-input id="inputClassify" v-model="ruleForm.classify" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="容量(m³)：">
      <el-input id="inputBox" v-model="ruleForm.box" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="目标温度(℃)：">
      <el-input id="inputTarget" v-model="ruleForm.target" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="阈值(℃)：">
      <el-input v-model="ruleForm.threshold" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="单次需热(GJ)：">
      <el-input v-model="ruleForm.total" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="所属用户ID：">
      <el-input v-model="ruleForm.uid" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="管道数量：">
      <el-input v-model="ruleForm.channel" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="效率(GJ/h)：">
      <el-input v-model="ruleForm.efficiency" class="selWidth"></el-input>
    </el-form-item>
    <el-form-item label="站点地址：">
      <el-input @change="mapSearch" id="mapAddress" placeholder="请输入地址按回车检索位置" v-model="ruleForm.address"
                class="selWidth"></el-input>
      <el-input type="hidden" style="display: none" id="mapAddressLat" v-model="ruleForm.lat"></el-input>
      <el-input type="hidden" style="display: none" id="mapAddressLng" v-model="ruleForm.lng"></el-input>
      <div id="map"></div>
      <div id="panel"></div>
    </el-form-item>
    <el-form-item label="简介：">
      <el-input v-model="ruleForm.info" type="textarea" class="selWidth"></el-input>
    </el-form-item>

    <el-form-item label="状态">
      <el-radio-group v-model="ruleForm.status">
        <el-radio label="1">正常</el-radio>
        <el-radio label="2">触发阈值</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="连接状态">
      <el-radio-group v-model="ruleForm.online">
        <el-radio label="1">在线</el-radio>
        <el-radio label="2">离线</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import {
    groupListApi,
    levelListApi,
    tagListApi,
    userInfoApi,
    userUpdateApi,
    userSaveApi,
    siteInfoApi, siteUpdateApi, siteSaveApi, userListApi
  } from '@/api/user'

  const defaultObj = {
    type:'1',
    birthday: '',
    cardId: '',
    id: null,
    mark: '',
    phone: '',
    realName: '',
    addres: '',
    groupId: '',
    level: '',
    isPromoter: false,
    status: false,
  }
  export default {
    name: "SiteEdit",
    props: {
      uid: {
        type: Number,
        default: null
      }
    },
    data() {
      return {
        ruleForm: Object.assign({}, defaultObj),
        groupData: [],
        labelData: [],
        labelLists: [],
        levelList: [],
        groupList: [],
        rules: {},
        map: null,
        userList:[],
      }
    },
    mounted() {
      this.getUserList()
      if (this.uid > 0) {
        this.siteInfo()
      }
      this.map = new AMap.Map("map", {
        center: [this.ruleForm.lat ? this.ruleForm.lat : 106.56288, this.ruleForm.lng ? this.ruleForm.lng : 29.556742 ], // [107.755852, 29.590834],
        resizeEnable: true,
        expandZoomRange: true,
        zooms: [3, 20],
        zoom: 10.5, //8.35,
        showBuildingBlock: true,
        showLabel: true,
      });
      let siteMarker = new AMap.Marker({
        position: new AMap.LngLat(this.ruleForm.lat ? this.ruleForm.lat : 106.56288, this.ruleForm.lng ? this.ruleForm.lng : 29.556742),
        offset: new AMap.Pixel(-8, 0)
      })
      this.map.add(siteMarker)

    },
    methods: {
      inputToDisabled(type){
        if(type =='1'){
          document.querySelector("#inputClassify").disabled = false
          document.querySelector("#inputClassify").parentNode.className = document.querySelector("#inputClassify").parentNode.className.replaceAll('is-disabled','')
          document.querySelector("#inputTarget").disabled = true
          document.querySelector("#inputTarget").parentNode.className += ' is-disabled'
          document.querySelector("#inputBox").disabled = true
          document.querySelector("#inputBox").parentNode.className += ' is-disabled'
          document.querySelector("#inputPriceItem").querySelector('.el-form-item__label').innerHTML = '单价（元/GJ）'
        }else{
          document.querySelector("#inputBox").disabled = false
          document.querySelector("#inputBox").parentNode.className = document.querySelector("#inputBox").parentNode.className.replaceAll('is-disabled','')
          document.querySelector("#inputClassify").disabled = true
          document.querySelector("#inputClassify").parentNode.className += ' is-disabled'
          document.querySelector("#inputTarget").disabled = false
          document.querySelector("#inputTarget").parentNode.className = document.querySelector("#inputBox").parentNode.className.replaceAll('is-disabled','')
          document.querySelector("#inputPriceItem").querySelector('.el-form-item__label').innerHTML = '单价（元/kwh）'
        }
      },
      // 用户列表
      getUserList () {
        userListApi({ page: 1, limit: 9999,userType:''}).then(res => {
          this.userList = res.list
        })
      },
      modalPicTap (tit, num) {
        const _this = this
        this.$modalUpload(function(img) {
          tit==='1'&& num === 'icon' ? _this.ruleForm.cover = img[0].sattDir : _this.ruleForm.cover = img[0].sattDir
        },tit , 'user')
      },
      // 详情
      mapSearch(address) {
        let that = this;
        AMap.plugin(["AMap.PlaceSearch"], function () {
          //构造地点查询类
          var placeSearch = new AMap.PlaceSearch({
            pageSize: 3, // 单页显示结果条数
            pageIndex: 1, // 页码
            city: "023", // 兴趣点城市
            citylimit: true,  //是否强制限制在设置的城市内搜索
            map: that.map, // 展现结果的地图实例
            panel: "panel", // 结果列表将在此容器中进行展示。
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          //关键字查询
          placeSearch.search(address)
          placeSearch.on('selectChanged',function (e) {
              document.querySelector('#mapAddress').value = e.selected.data.address
          })
          //变更地址和经纬度
          placeSearch.on('listElementClick', function (e) {
            that.ruleForm.addres = e.data.address
            that.ruleForm.lat = e.data.location.lng
            that.ruleForm.lng = e.data.location.lat
          })
          placeSearch.on('markerClick', function (e) {
            that.ruleForm.addres = e.data.address
            that.ruleForm.lat = e.data.location.lng
            that.ruleForm.lng = e.data.location.lat
          })

        });
      },
      // 详情
      siteInfo() {
        siteInfoApi({id: this.uid}).then(async res => {
          this.ruleForm = res
          this.inputToDisabled(this.ruleForm.type)

        })
      },
      // 分组列表
      groupLists() {
        groupListApi({page: 1, limit: 9999}).then(async res => {
          this.groupList = res.list
        })
      },
      //标签列表
      getTagList() {
        tagListApi({page: 1, limit: 9999}).then(res => {
          this.labelLists = res.list
        })
      },
      // 等级列表
      levelLists() {
        levelListApi({page: 1, limit: 9999, isShow: 1, isDel: 0}).then(async res => {
          this.levelList = res.list
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.uid > 0) {
              this.ruleForm.tagId = this.labelData.join(',')
              siteUpdateApi({id: this.ruleForm.id}, this.ruleForm).then(async res => {
                this.$message.success('编辑成功')
                this.$parent.$parent.visible = false
                this.$parent.$parent.getList()
              })
            } else {
              this.ruleForm.tagId = this.labelData.join(',')
              siteSaveApi(this.ruleForm).then(async res => {
                console.log(res)
                this.$message.success('编辑成功')
                this.$parent.$parent.visible = false
                this.$parent.$parent.getList()
              })
            }

          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.$emit('resetForm');
      }
    }
  }
</script>

<style scoped>
  .selWidth {
    width: 90%;
  }

  #map {
    width: 90%;
    height: 300px;
  }

  #panel {
    width: 30%;
    position: absolute;
    top: 35px;
    opacity: 0.9;
  }
</style>
